<template>
  <el-cascader 
    ref="cascader" 
    size="mini" 
    :props="prop" 
    :show-all-levels="false" 
    clearable 
    expand-trigger="hover"
    @change="handle_select" 
    v-model="areaId"
  />
</template>

<script>
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
export default {
  props: {
    area_id: {
      type: Number | String,
      default: null,
    },
  },
  data() {
    let accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    let areaId = accountInfo.areaId,
        areaName = accountInfo.areaName,
        lvl = accountInfo.areaLvl;
    return {
      areaId: null,
      prop: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { data, value} = node;
          
          if (data == undefined) {
            resolve([{ value: areaId, label: areaName, lvl, leaf: lvl == 4 }]);
          } else {
            if (data.lvl >= 4) {
              resolve();
              return;
            }
            areaId = value;
            lvl = data.lvl;
            $budgetAPI.getCompanyByLvl(
              {
                areaId,
                lvl,
              },
              (res) => {
                if (res.code == 0) {
                  let nodes = res.content.map((item, index) => {
                    return {
                      value: item.areaId,
                      label: item.areaName,
                      lvl: item.areaLvl,
                      leaf: item.areaLvl == 4
                    };
                  });
                  resolve(nodes);
                } else {
                  this.alertError(res);
                }
              }
            );
          }
        },
      },
    };
  },
  methods: {
    handle_select(v) {
      if(!v){ return }
      let id = v[v.length - 1];
      this.$emit("change", id)
      this.$emit("update:area_id", id);
      let data = this.$refs.cascader.getCheckedNodes()[0]
          ? this.$refs.cascader.getCheckedNodes()[0].data
          : "";
      if (data) {
        this.$emit("update:area_name", data.label);
      }
    },
  },
};
</script>

<style lang="scss">
</style>
